<template>
  <div>
    <el-dialog title="新增产品" :visible.sync="dialogVisible" width="500px" :before-close="closeEditDialog"
      :close-on-click-modal="false" :append-to-body="true">
      <el-form :model="addInfo" :rules="rules" ref="refAddInfo" label-width="110px">

        <el-form-item size="small" label="产品名称" prop="name">
          <el-input clearable v-model.trim="addInfo.name" placeholder="请输入" maxlength="30"></el-input>
        </el-form-item>

        <el-form-item size="small" label="产品类型" prop="deviceType">
          <el-input clearable v-model.trim="addInfo.deviceType" placeholder="请输入" maxlength="32"
            oninput="value=value.replace(/[^\w_]/g,'');"></el-input>
        </el-form-item>

        <el-form-item size="small" label="通讯协议类型" prop="protocolType">
          <el-select v-model="addInfo.protocolType" filterable placeholder="请选择" style="width: 350px;"
            class="elSelect">
            <el-option v-for="(item, i) in protocolTypeList" :key="i" :label="item.orgName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item size="small" label="设备数据格式" prop="dataFormat">
          <el-input clearable v-model.trim="addInfo.dataFormat" placeholder="请输入" maxlength="32"></el-input>
        </el-form-item>

        <el-form-item size="small" label="产品图片" prop="pic">
          <el-upload :class="{ disabled: uploadDisabled }" :on-remove="handleRemove" :on-change="uploadSectionFile"
            :action="baseUrl" list-type="picture-card" accept=".jpg,.png" :on-preview="handlePictureCardPreview"
            :headers="headers" :before-upload="beforeAvatarUpload" :on-success="handleSuccessFunction" :limit='1'
            :on-exceed="handleExceedScene" :file-list="fileList" :on-error="uploadFileError">
            <i class="el-icon-plus"></i>
          </el-upload>

        </el-form-item>

        <!-- <el-form-item size="small" label="产品ID">
          <el-input clearable v-model.trim="addInfo.productId" placeholder="请输入产品ID" maxlength="8"
            oninput="value=value.replace(/[^\w_]/g,'');"></el-input>
        </el-form-item>
        <el-form-item size="small" label="产品密钥">
          <el-input clearable v-model.trim="addInfo.masterApiKey" placeholder="请输入产品密钥" maxlength="32"
            oninput="value=value.replace(/[^\w_]/g,'');"></el-input>
        </el-form-item> -->

        <el-form-item size="small" label="所属行业" prop="industry">
          <el-autocomplete clearable @clear="clearAlarmFactor" v-model="addInfo.industry"
            :fetch-suggestions="querySearch" placeholder="请输入" @select="handleSelect" style="width: 350px"
            :maxlength="10"></el-autocomplete>
        </el-form-item>

        <el-form-item size="small" label="产品描述" prop="description">
          <el-input type="textarea" :rows="2" placeholder="请输入" maxlength="100" v-model.trim="addInfo.description"
            resize='none' :autosize="{ minRows: 2, maxRows: 5 }">
          </el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" @click="editSubmit" v-preventReClick="1000" class="confirm-button">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible2" class="el_dialog">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { handleTree } from "@utils/trans-tree";
import { provinceCityAreaArray } from "@/utils/province-city-area";
import { reqProductAdd } from "@/api/api";
import { mapState } from "vuex";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
// import "@components/vue-treeselect.less"; //树形选择器
import "@components/vue-treeselect.less";
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import asc from "@utils/asc.js"; //加密解密

export default {
  name: "add",
  props: ["floor"],
  components: { treeselect },
  data() {
    return {
      headers: {
        token: asc.decrypt(sessionStorage.getItem("token")),
      },
      fileList: [],
      dialogImageUrl: "",
      dialogVisible2: false,
      projectList: [], //单位数据
      provinceCityAreaData: provinceCityAreaArray,
      dialogVisible: false,
      addInfo: {
        name: "",
        deviceType: "",
        protocolType: "",
        dataFormat: "",
        // manufacturerName: "",
        industry: "",
        description: "",
        pic: "",
      },
      protocolTypeList: [
        {
          id: "MQTT",
          label: "MQTT",
        },
        {
          id: "CoAP",
          label: "CoAP",
        },
        {
          id: "HTTP",
          label: "HTTP",
        },
        {
          id: "HTTPS",
          label: "HTTPS",
        },
        {
          id: "Modbus",
          label: "Modbus",
        },
        {
          id: "ONVIF",
          label: "ONVIF",
        },
        {
          id: "OPC-UA",
          label: "OPC-UA",
        },
        {
          id: "OPC-DA",
          label: "OPC-DA",
        },
        {
          id: "Other",
          label: "Other",
        },
      ],
      // 表单验证规则
      rules: {
        productId: [
          { required: true, message: "请输入产品ID", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        deviceType: [
          { required: true, message: "请输入产品类型", trigger: "blur" },
        ],
        protocolType: [
          { required: true, message: "请选择通讯协议类型", trigger: "change" },
        ],
        dataFormat: [
          { required: true, message: "请输入设备数据格式", trigger: "blur" },
        ],
        manufacturerName: [
          { required: true, message: "请输入厂商名称", trigger: "blur" },
        ],
        pic: [
          { required: true, message: "请选择上传产品图片", trigger: "change" },
        ],
      },
      restaurants: [],
      uploadDisabled: false, //加号默认显示
    };
  },
  watch: {},
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [
        { value: "服务" },
        { value: "安防" },
      ];
    },
    handleSelect(item) {
      // console.log(item);
    },
    // 清除告警因素
    clearAlarmFactor() {
      this.restaurants = this.loadAll();
    },
    uploadSectionFile(file, fileList) {
      if (fileList.length >= 1) {
        this.uploadDisabled = true; //隐藏加号
      }
    },
    //上传失败
    uploadFileError(err, file, fileList) {
      this.uploadDisabled = false;
    },
    // //删除照片
    handleRemove(file) {
      this.addInfo.pic = "";
      setTimeout(() => {
        this.uploadDisabled = false;
      }, 1000);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      let isJPG = true;
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        this.$modal.notifyWarning("图片只能是 jpg/png 格式!");
        isJPG = false;
      }
      let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
      if (!isLt) {
        this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
        this.uploadDisabled = false;
        isJPG = false;
      }
      return isJPG;
    },
    // 上传成功
    handleSuccessFunction(response, file, fileList) {
      this.addInfo.pic = file.response.data.url;
    },
    // 文件超出个数限制时的钩子
    handleExceedScene() {
      this.$modal.notifyWarning(`产品图片只能上传一张图片`);
    },
    // 点击
    async editSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          const res = await reqProductAdd(this.addInfo);
          // console.log(res);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("添加产品成功");
          this.$parent.ProductList();
          this.closeEditDialog();
        }
      });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.uploadDisabled = false;
      this.addInfo = {
        name: "",
        deviceType: "",
        protocolType: "",
        dataFormat: "",
        industry: "",
        description: "",
        pic: "",
      };
      this.fileList = [];
      this.$refs.refAddInfo.resetFields();
      this.dialogVisible = false;
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
  created() {
    this.baseUrl = `${this.$baseURL_copy}file/upload`;
  },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 隐藏加号
/deep/ .disabled .el-upload--picture-card {
  display: none !important;
}

/deep/ .el_dialog .el-dialog__body {
  margin-bottom: 20px;
}
</style>